package com.andy.beef.app.util

import com.andy.beef.login.bean.TokenBean
import com.andy.beef.login.bean.UserInfoBean
import com.blankj.utilcode.util.GsonUtils
import com.tencent.mmkv.MMKV

/**
 * @creator:LuoFan
 * @date:2022/9/30
 * @description:
 */
object LocalDataUtil {

    private const val KEY_TOKEN = "token"

    private const val KEY_USER_INFO = "userInfo"

    private const val KEY_LOGIN_PHONE = "loginPhone"

    private var userInfoBean: UserInfoBean? = null

    private var token: String? = null

    fun getUserInfo(): UserInfoBean {
        if (userInfoBean == null) {
            val jsonStr = MMKV.defaultMMKV().getString(KEY_USER_INFO, "")
            userInfoBean = GsonUtils.fromJson(jsonStr, UserInfoBean::class.java)
        }
        return userInfoBean ?: UserInfoBean()
    }

    fun saveUserInfo(bean: UserInfoBean) {
        userInfoBean = bean
        val jsonStr = GsonUtils.toJson(bean)
        MMKV.defaultMMKV().putString(KEY_USER_INFO, jsonStr)
    }

    fun getToken(): String {
        if (token == null) {
            token = MMKV.defaultMMKV().getString(KEY_TOKEN, "")
        }
        return token ?: ""
    }

    fun saveToken(tokenBean: TokenBean) {
        token = tokenBean.token
        MMKV.defaultMMKV().putString(KEY_TOKEN, tokenBean.token)
    }

    fun clearToken() {
        token = null
        MMKV.defaultMMKV().putString(KEY_TOKEN, "")
    }

    fun saveLoginPhone(phone: String) {
        MMKV.defaultMMKV().putString(KEY_LOGIN_PHONE, phone)
    }

    fun getLoginPhone(): String? {
        return MMKV.defaultMMKV().getString(KEY_LOGIN_PHONE, "")
    }

}